﻿using DevExpress.XtraReports.UI;
using ReportDesignerServer.Common;

public class CustomReportStorageWebExtension : DevExpress.XtraReports.Web.Extensions.ReportStorageWebExtension
{
    readonly string ReportDirectory;
    const string FileExtension = ".repx";
    public CustomReportStorageWebExtension(IWebHostEnvironment env)
    {
        ReportDirectory = Path.Combine(Environment.CurrentDirectory, "Reports");
        NLogHelper.GetLog().Info("路径1:" + Environment.CurrentDirectory);
        NLogHelper.GetLog().Info("路径2:" + env.ContentRootPath);
        if (!Directory.Exists(ReportDirectory))
        {
            Directory.CreateDirectory(ReportDirectory);
        }
    }

    public override bool CanSetData(string url) { return true; }
    public override bool IsValidUrl(string url) { return true; }
    public override byte[] GetData(string url)
    {
        try
        {
            var paras = url.Split('|');
            var fileName = paras[0];
            var filePath = Path.Combine(ReportDirectory, fileName + FileExtension);
            NLogHelper.GetLog().Info("获取报表文件路径:" + filePath);
            if (!File.Exists(filePath))
            {
                XtraReport report = new XtraReport();
                report.SaveLayoutToXml(filePath);
            }
            string res = File.ReadAllText(filePath);
            NLogHelper.GetLog().Info("获取报表文件内容:" + res);
            return File.ReadAllBytes(filePath);
        }
        catch (Exception)
        {
            throw new DevExpress.XtraReports.Web.ClientControls.FaultException(
                string.Format("找不到报表 '{0}'.", url));
        }
    }

    public override Dictionary<string, string> GetUrls()
    {
        NLogHelper.GetLog().Info("GetUrls");
        return Directory.GetFiles(ReportDirectory, "*" + FileExtension)
                                 .Select(Path.GetFileNameWithoutExtension)
                                 .ToDictionary<string, string>(x => x);
    }

    public override void SetData(XtraReport report, string url)
    {
        NLogHelper.GetLog().Info("SetData");
        var paras = url.Split('|');
        var fileName = paras[0];
        report.SaveLayoutToXml(Path.Combine(ReportDirectory, fileName + FileExtension));
    }

    public override string SetNewData(XtraReport report, string defaultUrl)
    {
        NLogHelper.GetLog().Info("SetNewData");
        SetData(report, defaultUrl);
        return defaultUrl;
    }
}